<template>
  <div class="documentManage">
    <header class="crumbs_arr_box">
      <span @click="router_change(null, true, -1)">返回</span>
      <i></i>
      <span>
        <template v-if="edit_obj.id">文档编辑</template>
        <template v-else>添加文档</template>
      </span>
    </header>
    <section>
      <!-- 文档基本信息 -->
      <div class="doc_txt">
        <span class="doc_left">文档标题 (必填)</span>
        <el-input
          class="el_inp"
          :maxlength="18"
          placeholder="请输入文档标题"
          v-model="edit_obj.name"
          clearable
        ></el-input>
      </div>
      <div class="doc_txt">
        <span class="doc_left">文档归属 (必填)</span>
        <el-cascader
          :props="{ checkStrictly: true }"
          class="el_sel"
          v-model="parent"
          placeholder="试试搜索：文档名"
          :options="options"
          filterable
        ></el-cascader>
      </div>
      <!-- 富文本编译器盒子 -->
      <div class="edit_box">
        <quill-editor
          ref="myTextEditor"
          :options="config"
          v-model="edit_obj.content"
          style="height:90%;width:100%"
        ></quill-editor>
      </div>
      <!-- 文档递交 -->
      <div class="doc_txt doc_submit">
        <span class="doc_left">
          <!-- 新增文档进入 -->
          <template v-if="!edit_obj.id">
            <el-button :disabled="loading" @click="new_document(0)" size="mini" type="primary">保存</el-button>
            <el-button
              :disabled="loading"
              @click="new_document(1)"
              size="mini"
              type="primary"
              plain
            >发布</el-button>
          </template>
          <!-- 编辑文档进入 -->
          <template v-if="edit_obj.id">
            <el-button :disabled="loading" @click="edit_document(0)" size="mini" type="primary">保存</el-button>
            <el-button
              :disabled="loading"
              @click="edit_document(1)"
              size="mini"
              type="primary"
              plain
            >发布</el-button>
          </template>
        </span>
      </div>
    </section>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import application from "@/utils/api/application.js";
import config from "./config.js"; // 富文本编译器配置
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  name: "documentManage",
  components: {
    quillEditor
  },
  data() {
    return {
      documentList: [],
      parent: [],
      edit_obj: {},
      options: [],
      loading: false,
      config
    };
  },
  async created() {
    this.edit_obj = this.$store.state.application.edit_obj.id
      ? this.$store.state.application.edit_obj
      : JSON.parse(this.$route.query.editObj);
    let resTree =  this.treeChange();
    console.log(resTree)
    // 为了兼容归属组件接受类型，转换 parent  为  数组类型
    this.int_arr();
  },
  methods: {
    async treeChange() {
      this.documentList = await this.query();
      this.options = this.document_options(
        this.tree_data(this.documentList),
        this.edit_obj
      );
      this.options.unshift({
        value: 0,
        label: "无归属,一级文档"
      });
    },
    // 数据结构层次化函数
    tree_data(arr, level = 1, id = 0) {
      let tree_arr = [];
      let box_arr = [];
      arr.map(_i => {
        if (_i.level > level) {
          tree_arr.push(_i);
        }
        if (_i.level == level && _i.parent == id) {
          box_arr.push(_i);
        }
      });
      box_arr.map(_i => {
        _i.children = this.tree_data(tree_arr, level + 1, _i.id);
      });
      return box_arr;
    },
    // 多维数组转一维数组
    arr_change(arr) {
      let _arr = [];
      arr.map(_i => {
        _arr.push({
          id: _i.id,
          parent: _i.parent
        });
        if (_i.children && _i.children.length > 0) {
          let res = this.arr_change(_i.children);
          _arr = [..._arr, ...res];
        }
      });
      return _arr;
    },
    // 为了兼容归属组件接受类型，转换 parent  为  数组类型
    int_arr() {
      this.parent = [];
      let _p = this.edit_obj.parent;
      let _arr = this.arr_change(this.options);
      if (this.edit_obj.parent == 0 || !this.edit_obj.parent) {
        this.parent = [0];
        return;
      }
      for (let i = 0; i <= _arr.length - 1; i++) {
        if (_arr[i].id == _p) {
          _p = _arr[i].parent;
          this.parent.unshift(_arr[i].id);
          _arr.splice(i, 1);
          i = 0;
        }
      }
    },
    // 页面跳转
    router_change(path, bool, loop) {
      if (bool) {
        this.$router.go(loop);
      }
    },
    // 文档归属筛选函数
    document_options(arr, obj) {
      let _arr = [];
      arr.map(_i => {
        if (_i.id == obj.id) {
          return;
        }
        let _sub_obj = {
          value: _i.id,
          label: _i.name
        };

        if (_i.children.length > 1) {
          _sub_obj.children = this.document_options(_i.children, obj);
        }
        if (_i.children.length == 1 && _i.children[0].id !== obj.id) {
          _sub_obj.children = this.document_options(_i.children, obj);
        }
        _arr.push(_sub_obj);
      });
      return _arr;
    },
    // 新增文档进入，调取接口
    async new_document(status) {
      if (
        !this.parent[this.parent.length - 1] &&
        this.parent[this.parent.length - 1] !== 0
      ) {
        this.$message.error("请选择文档归属");
        return;
      }
      if (!this.edit_obj.name) {
        this.$message.error("请填写文档标题");
        return;
      }
      this.loading = true;
      let res = await application.document_add({
        name: this.edit_obj.name,
        content: this.edit_obj.content,
        parent: this.parent[this.parent.length - 1],
        status: status
      });
      if (res.success) {
        this.loading = false;
        this.$message({
          message: "操作成功",
          type: "success"
        });
        // this.treeChange();
        this.router_change(null, true, -1);
      }
    },
    // 数据请求函数
    async query() {
      let res = await application.document_list({});
      if (res.success) {
        return res.value.list;
      } else {
        return [];
      }
    },
    // 编辑文档进入，调取接口
    async edit_document(status) {
      // 根据树形节点数据 当前编辑文档 转为 结果集
      function treeToList(arr, bool, obj, parent, status) {
        let _arr = [];

        for (let i = 0; i <= arr.length - 1; i++) {
          let _obj = {
            id: arr[i].id,
            content: arr[i].content,
            level: arr[i].level,
            name: arr[i].name,
            parent: arr[i].parent,
            status: arr[i].status
          };
          if (arr[i].id == obj.id) {
            _obj.content = obj.content;
            _obj.name = obj.name;
            _obj.parent = parent;
            _obj.status = status;
            _obj.level = obj.level;
            bool = true;
            _arr.push(_obj);
            if (arr[i].children && arr[i].children.length > 0) {
              let arrChildren = treeToList(
                arr[i].children,
                bool,
                obj,
                parent,
                status
              );
              _arr = [..._arr, ...arrChildren];
            }
            return _arr;
          }
          if (bool) {
            _arr.push(_obj);
          }
          if (arr[i].children && arr[i].children.length > 0) {
            let arrChildren = treeToList(
              arr[i].children,
              bool,
              obj,
              parent,
              status
            );
            _arr = [..._arr, ...arrChildren];
          }
        }
        return _arr;
      }
      // 根据树形节点，生成结果集 List
      let _tree = JSON.parse(JSON.stringify(this.tree_data(this.documentList)));
      let resArr = treeToList(
        _tree,
        false,
        this.edit_obj,
        this.parent[this.parent.length - 1],
        status
      );
      let docArr = [];
      if (this.documentList && this.documentList.length > 0) {
        docArr = this.documentList;
      } else {
        docArr = await this.query();
      }
      let num = 0;
      if (this.parent[this.parent.length - 1] == 0) {
        num = 1 - Number(this.edit_obj.level);
      } else {
        docArr.map(_i => {
          if (_i.id == this.parent[this.parent.length - 1]) {
            num = Number(_i.level) - this.edit_obj.level + 1;
          }
        });
      }
      resArr.map(_i => {
        _i.level += num;
      });

      resArr.map(_i => {
        if (!_i.parent && _i.parent !== 0) {
          this.$message.error("请选择文档归属");
          return;
        }
        if (!_i.name) {
          this.$message.error("请填写文档标题");
          return;
        }
      });

      this.loading = true;
      let res = await application.document_edit({
        documentDOList: resArr
      });
      this.loading = false;
      if (res.success) {
        this.$message({
          message: "操作成功",
          type: "success"
        });
        // this.treeChange();
        this.router_change(null, true, -1);
      }
    }
  },
  computed: {}
};
</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
}
section {
  width: 90%;
  margin: 10px auto 40px;
  // height: calc(84.6vh - 14px);
  // min-height: 96vh;
  .doc_txt {
    width: 88%;
    height: 60px;
    margin: 0 auto;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .doc_left {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 120px;
      text-align: center;
      line-height: 60px;
      font-size: 13px;
      letter-spacing: 2px;
      color: #515a6e;
      font-weight: bold;
    }
    .el_sel {
      width: 300px;
      transform: scale(1, 0.8);
    }
    .el_inp {
      width: 300px;
      transform: scale(1, 0.8);
    }
  }
  .doc_submit {
    height: 30px;
    .doc_left {
      width: 100%;
      justify-content: space-evenly;
    }
  }
  .edit_box {
    width: 86%;
    // height: 400px;
    height: 60vh;
    min-height: 400px;
    margin: 10px auto 30px;
    display: flex;
    justify-content: center;
  }
}
.documentManage {
  width: 100%;
  height: 100%;
  min-height: 88vh;
  margin: 0 auto;
}
// 面包屑样式
.crumbs_arr_box {
  cursor: pointer;
  width: 100%;
  padding-left: 40px;
  height: 30px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  line-height: 30px;
  span {
    text-align: center;
    display: flex;
    align-items: center;
  }
  i {
    display: inline-block;
    width: 2px;
    height: 18px;
    transform: rotate(20deg);
    background: #01b27a;
    margin: 0 16px;
  }
}
</style>
